package com.bifrost.admin.controller;

import com.alibaba.fastjson.JSON;
import com.bifrost.annotation.CurrentAdmin;
import com.bifrost.annotation.CurrentStore;
import com.bifrost.common.base.ServerResponse;
import com.bifrost.entity.User;
import com.bifrost.model.ResultModel;
import com.bifrost.model.SkuExcelModel;
import com.bifrost.model.excel.SellDetailReportExcelModel;
import com.bifrost.model.ro.StatementRO;
import com.bifrost.model.vo.PageVO;
import com.bifrost.service.AdminOrderService;
import com.bifrost.service.AdminUserService;
import com.bifrost.service.ProductService;
import com.bifrost.service.StoreService;
import com.bifrost.util.DateUtils;
import com.bifrost.util.ExcelReportUtils;
import com.bifrost.util.TransformUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 里昂
 * @com.bifrost.admin.controller
 * @wechat-mall
 * @lee Create Class on 2018/4/17
 */
@Api("后台报表相关接口")
@RestController
@RequestMapping("/admin/report")
@Slf4j
public class AdminReportController {


    @Autowired
    ProductService productService;
    @Autowired
    StoreService storeService;

    @ApiOperation("商品明细列表")
    @GetMapping("/sku/detail")
    public ResultModel skuDetail(@CurrentStore Long storeId,
                                    String storeIds , String externalIds,String categoryName ,  String brandName , String skuName , String minPrice , String maxPrice, String brandId , String available , @RequestParam(value = "sortOrder" , required = false, defaultValue = "0") String sortOrder,
                                    @RequestParam( defaultValue = "1") Integer page ,
                                    @RequestParam( defaultValue = "8") Integer pageSize) {
        PageVO pageVO = productService.skuDetailList(storeService.getMerchantStore(storeId),storeIds, externalIds ,categoryName , brandName, page, pageSize, sortOrder, minPrice, maxPrice, skuName, brandId, available);
        return ResultModel.ok().put("result" , pageVO);
    }

    @ApiOperation("商品明细列表")
    @GetMapping("/export/sku/detail")
    public void exportSkuDetail(@CurrentStore Long storeId,
                                 String storeIds , String externalIds,String categoryName , String brandName , String skuName , String minPrice , String maxPrice, String brandId , String available, HttpServletResponse resp){
        List<SkuExcelModel> skuExcelModels = productService.skuDetail(storeService.getMerchantStore(storeId),storeIds, externalIds ,categoryName , brandName,minPrice, maxPrice, skuName, brandId, available);
        if (CollectionUtils.isNotEmpty(skuExcelModels)){
            ExcelReportUtils.exportExcel(skuExcelModels,"商品库存报表","商品库存报表",SkuExcelModel.class,"商品库存报表.xls",resp);
        }
    }

    @Autowired
    AdminOrderService adminOrderService;
    @Autowired
    AdminUserService adminUserService;


    @ApiOperation("单品销售报表")
    @PostMapping("/sell/detail")
    public ServerResponse sellDetail(@CurrentAdmin Long userId, @RequestBody(required = false) StatementRO statementRO) {
        try {
            User user = adminUserService.findById(userId);
            boolean exportFlag = Boolean.valueOf(false);
            PageVO pageVO = adminOrderService.getSellDetailReport(user, statementRO, statementRO.getPageCode(), statementRO.getPageSize(), exportFlag);
            return ServerResponse.createBySuccess(pageVO);
        } catch (Exception e) {
            log.info("单品销售报表查询失败，失败原因：", e);
            return ServerResponse.createByErrorMsg("查询失败，请稍后重试");
        }

    }

    @ApiOperation("导出单品销售报表")
    @GetMapping("/sell/detail/export")
    public void exportSellDetail(@CurrentAdmin Long userId,
                                 @RequestParam String statementRO,
                                 HttpServletRequest req, HttpServletResponse resp) {
        StatementRO ro = JSON.parseObject(statementRO, StatementRO.class);
        try {
            User user = adminUserService.findById(userId);
            boolean exportFlag = Boolean.valueOf(true);
            PageVO pageVO = adminOrderService.getSellDetailReport(user, ro, ro.getPageCode(), ro.getPageSize(), exportFlag);
            if (CollectionUtils.isEmpty(pageVO.getRecordList())) {
                log.error("导出的单品销售报表信息为空，请重新选择需要导出的明细信息");
            }
            List<SellDetailReportExcelModel> sellDetailReportExcelModels = TransformUtils.transformToSellDetailReportExcelModel(pageVO.getRecordList());
            if (CollectionUtils.isNotEmpty(sellDetailReportExcelModels)) {
                String startDate = "";
                String endDate = "";
                if (StringUtils.isNotBlank(ro.getStartDate())) {
                    startDate = DateUtils.format(DateUtils.parse(ro.getStartDate(), DateUtils.DEFAULT_DATE_FORMAT), DateUtils.DATE_PATTERN_ONE);
                }
                if (StringUtils.isNotBlank(ro.getEndDate())) {
                    endDate = DateUtils.format(DateUtils.parse(ro.getEndDate(), DateUtils.DEFAULT_DATE_FORMAT), DateUtils.DATE_PATTERN_ONE);
                }
                String title = String.format("%s-%s单品销售报表", startDate, endDate);
                ExcelReportUtils.exportExcel(sellDetailReportExcelModels, title, "单品销售报表", SellDetailReportExcelModel.class, title + ".xls", resp);
            }
        } catch (Exception e) {
            log.info("单品销售报表导出失败，失败原因：", e);
            throw new RuntimeException("导出单品销售报表信息失败");
        }

    }


}
